package com.zline.foodraise.ui.activity;

import android.graphics.Bitmap;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.baidu.mobstat.StatService;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.zline.foodraise.R;
import com.zline.foodraise.adapter.ProjectTemplateThumbListAdapter;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.TemplateBean;
import com.zline.foodraise.listener.RecyclerItemClicked;
import com.zline.foodraise.util.ImageUtil;
import com.zline.foodraise.util.StringUtils;
import com.zline.foodraise.util.TUtil;
import com.zline.foodraise.view.PosterTemplateView;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;

import java.util.ArrayList;

/**
 * Created by heshantao on 15/9/7.
 * 模板处理
 */
@EActivity(R.layout.activity_template_process)
public class TemplateProcessActivity extends ZlineActivity implements RecyclerItemClicked {
    private static final String LOG_TAG = TemplateProcessActivity.class.getSimpleName();
    //选择的本地图片地址
    @Extra
    String localPic;
    @Extra
    ArrayList<TemplateBean> templateArry;
    SparseArray<TemplateBean> templateBeanSparseArray;
    //选中是第几个模板
    @Extra
    int position;
    @ViewById(R.id.app_common_header_right_tv)
    TextView share_tv;
    @ViewById(R.id.template_fl)
    FrameLayout template_fl;
    @ViewById(R.id.template_thumbs_rv)
    RecyclerView thumbs_rv;
    PosterTemplateView templateView;
    @Bean
    ProjectTemplateThumbListAdapter thumbsAdapter;
    @StringRes(R.string.share)
    String share;
    Bitmap saveBitmap;
    @Bean
    ImageUtil imageUtil;
    //待保存图片的宽高
    int saveTemplateWidth;
    int saveTemplateHeight;
    TemplateBean templateBean;
    //模板Id
    long templateId;
    DisplayImageOptions options;

    @AfterViews
    void doSomeAfterViews() {
        getTemplateInfo(position);
        setThumbsRecyclerView();
        share_tv.setVisibility(View.VISIBLE);
        share_tv.setText(share);
    }


    void getTemplateInfo(int position) {
        templateBean = templateArry.get(position);
        if (options == null) {
            options = imageUtil.getDisplayImageOptions(
                    R.mipmap.default_template_thumb,
                    R.mipmap.default_template_thumb,
                    R.mipmap.default_template_thumb);
        }
        if (templateBean != null) {
            ImageLoader.getInstance().loadImage(templateBean.getAndroidImgUrl(), options,
                    new SimpleImageLoadingListener() {
                        @Override
                        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                            super.onLoadingComplete(imageUri, view, loadedImage);
                            if (templateBean != null) {
                                saveTemplateWidth = loadedImage.getWidth();
                                saveTemplateHeight = loadedImage.getHeight();
                                templateView = new PosterTemplateView(TemplateProcessActivity.this, templateBean, localPic, loadedImage);
                                template_fl.addView(templateView);
                            }

                        }
                    });
        }
    }

    //项目缩略图RecyclerView
    void setThumbsRecyclerView() {
        thumbs_rv.setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);//去除阴影
        GridLayoutManager layoutManager = new GridLayoutManager(this, 1);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        thumbs_rv.setLayoutManager(layoutManager);
        templateBeanSparseArray = new SparseArray<TemplateBean>();
        for (int i = 0; i < templateArry.size(); i++) {
            templateBeanSparseArray.put(i, templateArry.get(i));
        }
        thumbsAdapter.setAdapterData(templateBeanSparseArray);
        thumbsAdapter.setRecycleItemClickListener(this);
        templateId = templateBean.getTemplateId();
        thumbsAdapter.setSelectedTemplate(templateId);
        thumbs_rv.setAdapter(thumbsAdapter);
        thumbs_rv.setItemAnimator(new DefaultItemAnimator());//设置动画
    }


    //保存和分享
    void saveAndShareTemplate() {
        templateView.setDrawingCacheEnabled(true);
        saveBitmap = Bitmap.createScaledBitmap(templateView.getDrawingCache(),
                saveTemplateWidth, saveTemplateHeight, false);
        //这一步很关键，释放绘图缓存，避免出现重复的镜像
        templateView.destroyDrawingCache();
        String sharePicPath = imageUtil.saveImageToGallery(saveBitmap);
        if (StringUtils.isBlank(sharePicPath)) {
            TUtil.showShort(this, R.string.saved_fail);
        } else {
            TemplateShareActivity_.intent(this).templatePath(sharePicPath).start();
        }


    }

    @Click({R.id.app_common_header_left_icon_iv, R.id.app_common_header_right_tv})
    void onclick(View view) {
        switch (view.getId()) {
            case R.id.app_common_header_left_icon_iv:
                goback();
                break;
            case R.id.app_common_header_right_tv:
                saveAndShareTemplate();
                break;
            default:
                break;
        }
    }


    //通过缩略图变换模板
    void changeTemplate(int mposition) {
        TemplateBean bean = thumbsAdapter.getArrys().get(mposition);
        if (bean != null) {
            templateId = bean.getTemplateId();
            template_fl.removeView(templateView);
            getTemplateInfo(mposition);
            thumbsAdapter.setSelectedTemplate(templateId);
            thumbsAdapter.notifyDataSetChanged();
        }
    }


    @Override
    public void onRecyclerItemClicked(int position) {
        changeTemplate(position);
    }

    @Override
    public void onRecyclerItemClicked(int flag, int position) {

    }

    @Override
    public void onRecyclerItemClicked(int flag, int position, int parent) {

    }

    @Override
    public void onRecyclerClickedDelete(int position) {

    }

    //bitmap 销毁
    void destoryBitmap(Bitmap bitmap) {
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onResume(this);
        StatService.onPageStart(this, Constant.TEMPLATE_MADE);

    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPause(this);
        StatService.onPageEnd(this, Constant.TEMPLATE_MADE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destoryBitmap(saveBitmap);
    }
}
